<!-- 供应商管理-供应商审核列表  -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
  </pageHeader>
  <!-- <a-space class="client-list-header"> -->
  <div class="search-box">
    <a-space>
      <div>
        <a-input-group>
          <a-select
            :style="{ width: '120px' }"
            placeholder="请选择"
            v-model="currSelectVal"
          >
            <a-option value="number">供应商编号</a-option>
          </a-select>
          <a-input-search
            :style="{ width: 'auto' }"
            placeholder="请输入"
            v-model="currSelectSearch"
            @search="search"
            search-button
          />
        </a-input-group>
      </div>
      <!-- <div>
        <a-input-search
          :style="{ width: 'auto' }"
          placeholder="请输入区域、行业搜索"
          v-model="currNameSearch"
          search-button
          @click="search"
        >
          <template #button-icon>
            <icon-search />
          </template>
        </a-input-search>
      </div> -->
    </a-space>
    <div>
      <a-space>
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning">
          <template #icon>
            <icon-export rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>

        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </div>
  <!-- </a-space> -->
  <div style="padding: 10px">
    <tableTurn :tableData="getData" :args="args" ref="tableTurnRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        :title="item.name"
        v-for="(item, index) in selectedHeader"
        :key="index"
        :data-index="item.code"
        align="center"
        :width="200"
        :ellipsis="true"
        :tooltip="{
          position: 'top',
        }"
      >
        <template v-if="item.code === 'createdAt'" #cell="{ record }">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD HH:MM') }}
        </template>

        <template v-else-if="item.code === 'state'" #cell="{ record }">
          <div class="state">
            <div
              class="state-box"
              :class="
                record.state == 1
                  ? 'WaitSubmitted'
                  : record.state == 2
                  ? 'WaitSubmitted'
                  : record.state == 3
                  ? 'Pass'
                  : record.state == 4
                  ? 'Pass'
                  : record.state == 5
                  ? 'NoPass'
                  : 'Pass'
              "
            >
              <div
                style="
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                "
              >
                <span>{{
                  record.state == 2
                    ? '待审核'
                    : record.state == 4
                    ? '已通过'
                    : record.state == 5
                    ? '不通过'
                    : '合格供应商'
                }}</span>
              </div>
            </div>
          </div>
        </template>
      </a-table-column>
      <!-- 操作item -->
      <a-table-column align="center" :width="150" fixed="right" title="操作">
        <template #cell="{ record }">
          <!-- <a-button
            v-if="record.state === 2"
            type="text"
            @click="audit(record)"
            :style="{
              backgroundColor: '#31C27C',
              color: '#fff',
            }"
            >审核</a-button
          >
          <a-button v-if="record.state !== 2" type="text" @click="audit(record)"
            >查看详情</a-button
          > -->

          <a-tooltip v-if="record.state === 2" content="提交评审">
            <IconFont
              type="icon-shenhe"
              :size="20"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
                color: 'rgb(22, 93, 254)',
              }"
              @click="audit(record)"
            />
          </a-tooltip>

          <a-tooltip v-if="record.state !== 2" content="详情">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="audit(record)"
            />
          </a-tooltip>
        </template>
      </a-table-column>
    </tableTurn>
  </div>

  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    title="供应商审核列表表头设置"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
    :forbidList="forbidList"
  ></FormHeaderSetting>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, watchEffect, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import { GetSupplierLevelInfo } from '@/api/buy-management/supplier-management/base-setting';
  import {
    GetSupplierPrimaryList,
    DelSupplierPrimaryList,
    GetSupplierPrimaryHeaderList,
    PutSupplierPrimaryHeaderList,
  } from '@/api/buy-management/supplier-management/supplier-primary-list';
  import cloneDeep from 'lodash.clonedeep';
  import dayjs from 'dayjs';
  import { formHeaderSetting } from '@/types/global';

  const router = useRouter();
  const title = '供应商审核列表';
  const breadCrumb = ['采购管理', '供应商管理', '供应商审核列表'];

  const headerSetting = reactive<formHeaderSetting>({
    list: [],
  });

  const forbidList = reactive(['salesName']); // 禁止移动的表头， (销售员)

  // 表格配置
  const args = reactive({
    stripe: true,

    scroll: {
      y: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });
  let tableTurnRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  let currNameSearch = ref(''); // 储存搜索供应商名称的值
  let isFirstSelect = ref(true);

  // 获取列表数据
  const getData = async (pageData?: any) => {
    try {
      if (isFirstSelect.value) {
        const res = await GetSupplierPrimaryList({
          ...pageData,
          auditList: 2,
        });
        isFirstSelect.value = false;
        return Promise.resolve(res);
      } else {
        const res = await GetSupplierPrimaryList({
          ...pageData,
          name: currNameSearch.value,
          [currSelectVal.value]: currSelectSearch.value,
        });
        return Promise.resolve(res);
      }
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let levelList = reactive<any>({
    list: [],
  });
  const getLevelData = async () => {
    try {
      const { data } = await GetSupplierLevelInfo();
      levelList.list = data;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getLevelData();

  // 搜索按钮
  const search = () => {
    tableTurnRef.value.loadData();
  };

  // 重置按钮
  const reset = () => {
    currSelectSearch.value = '';
    currNameSearch.value = '';
    currSelectVal.value = '';
    tableTurnRef.value.loadData();
  };

  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      tableTurnRef.value.loadData();
    }
  };

  onMounted(() => {
    // 监听键盘事件
    window.addEventListener('keydown', keyDown);
  });

  // 获取表头设置列表
  const getHeaders = async () => {
    try {
      const tableHead = await GetSupplierPrimaryHeaderList({
        supplierType: 2,
        userId: 2,
      });
      headerSetting.list = tableHead.extends;
    } catch (error: unknown) {
      console.log(error);
    }
  };
  getHeaders();

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: formHeaderSetting['list'] = [];
    headerSetting.list.forEach((item) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  let formHeaderSettingVisible = ref<boolean>(false); // 是否显示表头设置组件

  // 表头设置按钮
  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  // 表头设置保存后返回的自定义事件
  const headerSave = async (headerList: formHeaderSetting['list']) => {
    try {
      const data = {
        userId: 2,
        supplierType: 2,
        extend: JSON.stringify(headerList),
      };
      await PutSupplierPrimaryHeaderList(data);
      headerSetting.list = [...headerList];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // 点击进入审核页面
  const audit = (record): void => {
    router.push({
      name: 'SupplierAudit',
      query: {
        supplierId: record.id,
        templateId: record.templateId,
        supLevelId: record.supLevelId,
        type: 'audit',
      },
    });
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
    margin-top: -7px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }
  .state {
    text-align: center;
    display: flex;
    justify-content: center;
    &-box {
      width: 50px;
      border-radius: 15px;
      line-height: 26px;
      color: #fff;
      height: 26px;
    }
    .WaitSubmitted {
      // 待提交
      background: #c9cdd4;
    }
    .Examining {
      // 审核中
      background: #165dff;
    }
    .Pass {
      // 已通过
      background: #31c27c;
    }
    .NoPass {
      //不通过
      background: #f53f3f;
    }
    .Qualified {
      // 合格
      background: #ff9a2e;
    }
  }
</style>
